package com.zhugang.week04;

/**
 * @program algorithms
 * @description: quickSort
 * @author: chanzhugang
 * @create: 2022/06/27 11:55
 */
public class QuickSort3 {


    public static void main(String[] args) {
        QuickSort3 quickSort3 = new QuickSort3();
        int[] a = new int[]{4, 5, 6, 1, 2, 3};
        quickSort3.quickSort(a, a.length);
        for (int i : a) {
            System.out.println(i);
        }
    }

    /**
     * 快排
     *
     * @param a
     * @param n
     */
    public void quickSort(int[] a, int n) {
        quickSort_r(a, 0, n - 1);
    }

    private void quickSort_r(int[] a, int p, int r) {
        // 找分区点，小于分区点的放左边，大于分区点的放右边
        if (p >= r) {
            return;
        }
        int q = partition(a, p, r);
        quickSort_r(a, p, q - 1);
        quickSort_r(a, q + 1, r);
    }

    private int partition(int[] a, int p, int r) {
        // [p, i] 是小于分区点的值
        int i = p - 1;
        for (int j = p; j < r; j++) {
            if (a[j] < a[r]) {
                // i + 1 和 j 交换
                swap(a, i + 1, j);
                i++;
            }
        }
        swap(a, i + 1, r);
        return i + 1;
    }

    private void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}